package com.boxin.ims.modules.wechat.utils;

import java.util.Map;


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatApiTicket;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessage;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessageFactory;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
//import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;

public class JsTicketUtils {
	
	public final static long TIME_OUT = 7100;	// 超时为7200秒
	
	private final static Logger logger = Logger.getLogger(JsTicketUtils.class);
	
//	private static Map<String , WechatApiTicket> ticketMap  = new HashMap<String, WechatApiTicket>();
	
	
	public static DefaultHttpClient httpclient;
	
	static {
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端
	}
	
	
	
	/**
	 * 
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:17:43
	 * @function <p> 获取一个缓存的 Token </p>
	 * @param weChat
	 * @return
	 */
	public static String  getJSAPITicket(WeChat weChat){
		
			//WechatApiTicket  ticket = (WechatApiTicket)CacheUtils.get("js_ticket_"+weChat.getAppId());
			WechatApiTicket  ticket = (WechatApiTicket) CacheUtils.get("js_ticket_"+weChat.getAppId());//JedisUtils.getObject("js_ticket_"+weChat.getAppId());
			
			if(isValiable(ticket)){
				System.out.println("当前JsTicket可用未超时.");
				//判断如果jsticket为空重新尝试拉取
				if(StringUtils.isEmpty(ticket.getToken())){
					String strToken = getNewToken(weChat);
					return strToken;
				}
				return ticket.getToken();
			}else{
				String strToken = getNewToken(weChat);
				return strToken;
			}
	}
	
	
	/**
	 * 
	 * @param weChat
	 * @return
	 */
	public static String  getJSAPITicketByUser(Long userId){
		
		 Map<Long, Map<String, String>> map = TokenUtils.getUserMap();
		 Map<String, String> temp = map.get(userId);
		
		 String appId = temp.get("appId");
		 String appSecret = temp.get("appSecret");
		
		return getJSAPITicket(appId, appSecret);
		
		
}
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-9-10  下午4:28:52
	 * @function <p> 删除缓存中的Token </p>
	 * @param weChat
	 */
	public static void removeJSAPITicket(String appId,String secret){
		CacheUtils.remove("js_ticket_"+appId);
//		JedisUtils.del("js_ticket_"+appId);
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-7-3  上午9:34:35
	 * @function <p> 根据appid,secret查找 accessToken </p>
	 * @param appId
	 * @param secret
	 * @return
	 */
	public static String getJSAPITicket(String appId,String secret){
		
			WechatApiTicket  token = (WechatApiTicket)CacheUtils.get("js_ticket_"+appId);
			if(isValiable(token)){
				System.out.println("当前Token可用未超时.");
				//判断如果jsticket为空重新尝试拉取
				if(StringUtils.isEmpty(token.getToken())){
					WeChat weChat = new WeChat();
					weChat.setAppId(appId);
					weChat.setAppSecret(secret);
					String strToken = getNewToken(weChat);
					return strToken;
				}
				return token.getToken();
			}else{
				WeChat weChat = new WeChat();
				weChat.setAppId(appId);
				weChat.setAppSecret(secret);
				String strToken = getNewToken(weChat);
				return strToken;
			}
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:17:14
	 * @function <p>当前的Token是否可用是否超时  </p>
	 * @param token
	 * @return
	 */
	private static boolean isValiable(WechatApiTicket token){
		if(token == null) return false;
		long now = System.currentTimeMillis();
		long diff = now - token.getStart() ;
		if(diff/1000 > TIME_OUT){
			return false;
		}
		return true;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:16:59
	 * @function <p> 重新获取一个新Token </p>
	 * @param weChat
	 * @return
	 */
	private static String getNewToken(WeChat weChat){
		HttpGet get = null;
		try {
			String token = TokenUtils.getAPIToken(weChat);
			if(StringUtils.isNotBlank(token)){
				get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi");
				HttpResponse response = httpclient.execute(get);
				String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
				JSONObject object = JSON.parseObject(jsonStr);
				String ticket = object.getString("ticket");
				
				
				if(StringUtils.isEmpty(ticket)){
					return getTicketFail(weChat);
				}
				
				WechatApiTicket  apiToken = new WechatApiTicket();
				apiToken.setAppId(weChat.getAppId());
				apiToken.setStart(System.currentTimeMillis());
				apiToken.setSecretKey(weChat.getAppSecret());
				apiToken.setToken(ticket);
//				JedisUtils.setObject("js_ticket_"+weChat.getAppId(), apiToken, 0);
				CacheUtils.put("js_ticket_"+weChat.getAppId(), apiToken);
//				CacheUtils.put("js_ticket_"+weChat.getAppId(), token);
				return ticket;
			}
			//CacheUtils.put("js_ticket_"+weChat.getAppId(), token);
			//String ticket = token.getToken();
			//System.out.println("生成新ticket:"+ticket);
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally{
			if (get != null) {
				get.abort();
			}
		}
		
		return null;
	}
	
	
	
	
	public static String getTicketFail(final WeChat weChat){
			
				Runnable runner = new Runnable() {
					
					String token = TokenUtils.getAPIToken(weChat);
					@Override
					public void run() {
						
						boolean flag =false;
						//5次尝试拉取
						for (int i = 0; i < 5; i++) {
							
							//通过token获取jsticket
							HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi");
							HttpResponse response;
							try {
								Thread.sleep(1000);
								
								response = httpclient.execute(get);
								String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
								
								JSONObject object = JSON.parseObject(jsonStr);
								String ticket = object.getString("ticket");
								
								if(StringUtils.isNotEmpty(ticket)){
									
									WechatApiTicket  apiToken = new WechatApiTicket();
									apiToken.setAppId(weChat.getAppId());
									apiToken.setStart(System.currentTimeMillis());
									apiToken.setSecretKey(weChat.getAppSecret());
									apiToken.setToken(ticket);
//									JedisUtils.setObject("js_ticket_"+weChat.getAppId(), apiToken, 0);
									CacheUtils.put("js_ticket_"+weChat.getAppId(), apiToken);
									System.out.println("生成新Token:"+ticket);
									
									flag=true;
									break;
								}
								
							} catch (Exception e) {
								e.printStackTrace();
							}finally{
								if (get != null) {
									get.abort();
								}
							}
							
						}
						
						 
					}
					
					
				};
				new Thread(runner).start();
		return "";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:25:36
	 * @function <p>  </p>
	 * @param args
	 */
	public static void main(String[] args) {
		
		String token="xZhK0wCEIhJjVFQHs4xjHRc9wsATE9FPh-3hopRyCHR0GRblzBuB0jyb8VbtfkAwDwxO6QsS9BcGpDzfFTUR0WQYbZdtgjus9puwy6WmR1E";
		//通过token获取jsticket
		try {
			//通过token获取jsticket
			HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi");
			HttpResponse response = httpclient.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			String ticket = object.getString("ticket");
			
			WechatApiTicket  apiToken = new WechatApiTicket();
			apiToken.setAppId("wxd5c07b37653b593b");
			apiToken.setStart(System.currentTimeMillis());
			apiToken.setSecretKey("6049fad2dfa8a13443371b169a0e7241");
			apiToken.setToken(ticket);
//			JedisUtils.setObject("ticket"+"wxd5c07b37653b593b", apiToken, 0);
			System.out.println("生成新Token:"+ticket);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
//		for(int i= 0;i<10;i++){
//			try {
//				Thread.sleep(1000);
//				System.out.println("第"+(i+1)+"个Token:"+token);
//				
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		
	}

	
	
	
	/**
	 * 
	 * @author 
	 * @time 2015-12-21
	 * @function <p> 获取一个缓存的 Token </p>
	 * @param weChat
	 * @return
	 */
	public static String  getJSAPITicketCard(WeChat weChat){
		
			WechatApiTicket  ticket = (WechatApiTicket)CacheUtils.get("ticket_card_"+weChat.getAppId());
			
			if(isValiable(ticket)){
				System.out.println("当前JsTicket可用未超时.");
				//判断如果jsticket为空重新尝试拉取
				if(StringUtils.isEmpty(ticket.getToken())){
					String strToken = getNewTokenCard(weChat);
					return strToken;
				}
				return ticket.getToken();
			}else{
				String strToken = getNewTokenCard(weChat);
				return strToken;
			}
	}
	/**
	 * @author 
	 * @time 2015-12-21
	 * @function <p> 重新获取一个新Token </p>
	 * @param weChat
	 * @return
	 */
	private static String getNewTokenCard(WeChat weChat){
		HttpGet get = null;
		try {
			//String accessToken= WechatMenuUtils.getAccessToken(weChat.getAppId(), weChat.getAppSecret());
			WechatApiTicket  token =  (WechatApiTicket) CacheUtils.get("ticket_card_"+weChat.getAppId());//JedisUtils.getObject("ticket_card_"+weChat.getAppId());
			
			if(!isValiable(token)){
				get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=wx_card");
				HttpResponse response = httpclient.execute(get);
				String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
				JSONObject object = JSON.parseObject(jsonStr);
				String ticket = object.getString("ticket");
				
				if(StringUtils.isEmpty(ticket)){
					return getTicketFailCard(weChat);
				}
				
				WechatApiTicket  apiToken = new WechatApiTicket();
				apiToken.setAppId(weChat.getAppId());
				apiToken.setStart(System.currentTimeMillis());
				apiToken.setSecretKey(weChat.getAppSecret());
				apiToken.setToken(ticket);
//				JedisUtils.setObject("ticket_card_"+weChat.getAppId(), apiToken, 0);
				CacheUtils.put("ticket_card_"+weChat.getAppId(), apiToken);
				CacheUtils.put("ticket_card_"+weChat.getAppId(), token);
			}
			CacheUtils.put("ticket_card_"+weChat.getAppId(), token);
			String ticket = token.getToken();
			System.out.println("生成新ticket:"+ticket);
			return ticket;
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally{
			if (get != null) {
				get.abort();
			}
		}
		
		return null;
	}
	
	public static String getTicketFailCard(final WeChat weChat){
		
		Runnable runner = new Runnable() {
			
			String token = TokenUtils.getAPIToken(weChat);
			@Override
			
			public void run() {
				
				boolean flag =false;
				//5次尝试拉取
				for (int i = 0; i < 5; i++) {
					
					
					//通过token获取jsticket
					HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=wx_card");
					HttpResponse response;
					try {
						Thread.sleep(1000);
						
						response = httpclient.execute(get);
						String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
						
						JSONObject object = JSON.parseObject(jsonStr);
						String ticket = object.getString("ticket");
						
						if(StringUtils.isNotEmpty(ticket)){
							
							WechatApiTicket  apiToken = new WechatApiTicket();
							apiToken.setAppId(weChat.getAppId());
							apiToken.setStart(System.currentTimeMillis());
							apiToken.setSecretKey(weChat.getAppSecret());
							apiToken.setToken(ticket);
//							JedisUtils.setObject("ticket_card_"+weChat.getAppId(), apiToken, 0);
							CacheUtils.put("ticket_card_"+weChat.getAppId(), apiToken);
							System.out.println("生成新Token:"+ticket);
							
							flag=true;
							break;
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}finally{
						if (get != null) {
							get.abort();
						}
					}
					
				}
				
				 
			}
			
			
		};
		new Thread(runner).start();
		return "";
	}
}
